package cn.mill.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mill.common.Context;
import cn.mill.common.Strategy;
import cn.mill.common.annotation.SPI;
import cn.mill.common.data.DataCommon;
import cn.mill.common.data.Item;
import cn.mill.common.data.ItemArray;
import cn.mill.common.message.Message;

@SPI("file")
public class DefaultStrategy implements Strategy<String, InputStream> {
	private static Logger logger = LoggerFactory.getLogger(DefaultStrategy.class);
	
	@Override
	public Message<String> write(Context invoke, ItemArray itemArray) {
		return new DefaultMessage<String>();
	}
	
	@Override
	public DataCommon<ItemArray> read(Context invoke, Message<InputStream> message) {
		DefaultData defaultData = new DefaultData();
		ItemArray array = new ItemArray();
		try {
			InputStreamReader inputReader = new InputStreamReader(message.getDataBlock());
			BufferedReader bf = new BufferedReader(inputReader);
			Item i = invoke.getAttachments().get("spilt");
			String spilt = i == null ? Constants.SPILT : (String) i.getValue();
			// 按行读取字符串
			String str;
			while ((str = bf.readLine()) != null) {
				logger.debug("line --->" + str);
				ItemArray itemArray = new ItemArray();
				String[] arr = str.split(spilt);
				for (int k = 0; k < arr.length; k++) {
					itemArray.addItem(new Item(null, "" + (k + 1), String.class, arr[k]));
				}
				array.addItem(new Item(null, "", ItemArray.class, itemArray));
			}
			bf.close();
			inputReader.close();
			message.getDataBlock().close();
		} catch (IOException e) {
			logger.error("", e);
			defaultData.setException(e);
			defaultData.setFine(false);
			return defaultData;
		}
		defaultData.setValue(array);
		defaultData.setFine(true);
		return defaultData;
	}
	
}
